import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 确保每次刷新应用时都清除登录信息，强制用户重新登录
localStorage.removeItem('token')
localStorage.removeItem('userInfo')
localStorage.removeItem('permissions')

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
 
  {
    path: '/home',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { 
          title: '仪表盘',
          icon: 'Dashboard'
        }
      },
      {
        path: 'analytics',
        name: 'Analytics',
        component: () => import('@/views/analytics/Analytics.vue'),
        meta: { 
          title: '分析页',
          icon: 'TrendCharts'
        }
      },
      {
        path: 'monitoring',
        name: 'Monitoring',
        component: () => import('@/views/monitoring/Monitoring.vue'),
        meta: { 
          title: '监控页',
          icon: 'Monitor'
        }
      },
      {
        path: 'template-center',
        name: 'TemplateCenter',
        component: () => import('@/views/template/TemplateCenter.vue'),
        meta: { 
          title: '模板中心',
          icon: 'Grid'
        }
      },
      {
        path: 'component-center',
        name: 'ComponentCenter', 
        component: () => import('@/views/component/ComponentCenter.vue'),
        meta: { 
          title: '组件中心',
          icon: 'Histogram'
        }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/users/UserList.vue'),
        meta: { 
          title: '用户管理',
          icon: 'User',
          permission: 'user.view'
        }
      },
      {
        path: 'roles',
        name: 'RoleManagement',
        component: () => import('@/views/roles/RoleList.vue'),
        meta: { 
          title: '角色管理',
          icon: 'UserFilled',
          permission: 'role.view'
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 通用管理系统`
  }

  // 强制所有首次访问和根路径访问重定向到登录页面
  if (to.path === '/' || from.path === '') {
    // 直接重定向到登录页面，不调用logout以避免API请求
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('permissions')
    // 手动重置store状态
    userStore.token = ''
    userStore.userInfo = null
    userStore.permissions = []
    next('/login')
    return
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth !== false) {
    if (!userStore.token) {
      next('/login')
      return
    }

    // 检查权限
    if (to.meta.permission && !userStore.hasPermission(to.meta.permission)) {
      next('/403')
      return
    }
  }

  // 如果已登录访问登录页面，重定向到仪表盘
  if (to.path === '/login' && userStore.token) {
    next('/home')
    return
  }

  next()
})

export default router
